package com.gdougms.tools;

import com.gdougms.entity.HttpMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.print.attribute.standard.PresentationDirection;
import java.util.concurrent.TimeUnit;

/**@Title
 * @Description 验证码生成发送的同时使用的写入redis以及读取redis的类
 * @Author iceF
 * @Date 2021/6/20
*/

@Slf4j
@Component
public class RedisCodeGetSet {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    ObjectFactory<HttpMessage> httpMessageObjectFactory;

    public HttpMessage readCode(String email, String code){
        HttpMessage httpMessage = httpMessageObjectFactory.getObject();
        String emailCount = "EmailCount"+email;
        String emailCode = "EmailCode"+email;
        String redisCode = (String) redisTemplate.opsForValue().get(emailCode);
        if(redisCode == null){
            log.info("验证码过期了");
            httpMessage.setResult(false);
            httpMessage.setMessage("验证码过期了,请重新发送");
            return httpMessage;
        }else{
            if (code.equals(redisCode)){
                log.info("验证成功");
                httpMessage.setResult(true);
                httpMessage.setMessage("验证成功");
            }else{
                log.info("验证码不相同");
                httpMessage.setResult(false);
                httpMessage.setMessage("验证码不相同,请重新填写");
            }
            return httpMessage;
        }
    }


    public HttpMessage writeCode(String email,String code){
        HttpMessage httpMessage = httpMessageObjectFactory.getObject();
        //24h已发送次数
        String emailCount = "EmailCount"+email;
        String emailCode = "EmailCode"+email;
        String count = (String) redisTemplate.opsForValue().get(emailCount);
        if(count == null){
            redisTemplate.opsForValue().set(emailCount,"1",24*60*60, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set(emailCode,code,180,TimeUnit.SECONDS);
            httpMessage.setResult(true);
            httpMessage.setMessage("验证码写入Redis成功");
            return httpMessage;
        }else if (Integer.parseInt(count) <= 5){
            redisTemplate.opsForValue().increment(emailCount);
            redisTemplate.opsForValue().set(emailCode,code,180,TimeUnit.SECONDS);
            httpMessage.setResult(true);
            httpMessage.setMessage("验证码写入Redis成功");
            return httpMessage;
        }else{
            log.info("你已经发送了5次验证码，请24h后再试。");
            httpMessage.setResult(false);
            httpMessage.setMessage("你已经发送了5次验证码，请24h后再试。");
            return httpMessage;
        }
    }

}
